<template>
	<view class="report-list">
		<!-- 导航栏 -->
		<nav-bar backUrl="/pages/my/my" :isTabbar="true"></nav-bar>
		<!-- 状态标签栏 -->
		<view class="status-tabs">
			<view 
				v-for="(tab, index) in statusTabs"
				:key="index"
				class="tab-item"
				:class="{ active: currentStatus === tab.value }"
				@tap="switchStatus(tab.value)"
			>
				<view class="tab-content">
					<text>{{ tab.label }}</text>
					<text class="count" v-if="tab.count > 0">({{ tab.count }})</text>
				</view>
			</view>
		</view>

		<!-- 售后列表 -->
		<view class="report-items">
			<view class="report-item" v-for="(item, index) in reportList" :key="index">
				<!-- 服务信息 -->
				<view class="service-info">
					<image class="service-image" :src="item.project && item.project.imgUrls ? item.project.imgUrls : ''" mode="aspectFill"></image>
					<view class="service-content">
						<view class="service-title">{{ item.project && item.project.projectName ? item.project.projectName : '未知项目' }}</view>
						<view class="service-meta">
							<text class="store">{{ item.store && item.store.storeName ? item.store.storeName : '未知门店' }}</text>
							<text class="technician">{{ item.technician && item.technician.technicianName ? item.technician.technicianName : '未知技师' }}</text>
						</view>
						<view class="service-time">{{ item.createTime || '未知时间' }}</view>
					</view>
					<view class="status-tag" :class="{
						'pending': item.status === 0,
						'processing': item.status === 1,
						'completed': item.status === 2,
						'rejected': item.status === 3
					}">
						{{ getStatusText(item.status) }}
					</view>
				</view>

				<!-- 反馈信息 -->
				<view class="feedback-info">
					<view class="feedback-types">
						<text class="type-tag" v-for="(type, tIndex) in item.feedbackTypes ? item.feedbackTypes.split(',') : []" :key="tIndex">
							{{ type }}
						</text>
					</view>
					<view class="feedback-content">{{ item.feedbackContent || '无反馈内容' }}</view>
					<!-- 媒体展示区域 -->
					<view class="media-list" v-if="item.mediaUrls">
						<view 
							v-for="(media, mediaIndex) in item.mediaUrls.split(',')"
							:key="mediaIndex"
							class="media-item"
						>
							<!-- 根据文件类型显示不同组件 -->
							<image 
								v-if="isImageUrl(media)"
								:src="media"
								mode="aspectFill"
								class="feedback-image"
								@tap="previewImage(item.mediaUrls.split(',').filter(url => isImageUrl(url)), mediaIndex)"
							></image>
							<video 
								v-else
								:src="media"
								class="feedback-video"
								:controls="false"
								:show-play-btn="true"
								:enable-progress-gesture="false"
								object-fit="cover"
							></video>
						</view>
					</view>
				</view>

				<!-- 处理结果 -->
				<view class="handle-result" v-if="item.handleResult">
					<view class="result-title">处理结果：</view>
					<view class="result-content">{{ item.handleResult }}</view>
					<view class="handle-time">处理时间：{{ item.handleTime }}</view>
				</view>
			</view>
		</view>

		<!-- 空状态 -->
		<view class="empty-state" v-if="reportList.length === 0">
			<text>暂无售后记录</text>
		</view>
	</view>
</template>

<script>
import NavBar from '@/components/nav-bar/nav-bar.vue'
export default {
	components: {
		NavBar
	},
	data() {
		return {
			currentStatus: -1, // 当前选中的状态
			statusTabs: [
				{ label: '全部', value: -1, count: 0 },
				{ label: '待处理', value: 0, count: 0 },
				{ label: '处理中', value: 1, count: 0 },
				{ label: '已完成', value: 2, count: 0 },
				{ label: '已驳回', value: 3, count: 0 }
			],
			reportList: [],
			limit: 10
		}
	},

	onLoad() {
		this.loadReportList(1)
		this.loadStatusCount()
	},

	methods: {
		// 切换状态
		switchStatus(status) {
			this.currentStatus = status
			this.loadReportList(2)
		},

		// 加载售后列表
		async loadReportList(tag) {
			try {
				const userInfoStr = uni.getStorageSync('userInfo')
				let userInfo = null
				
				if (userInfoStr) {
				  try {
				    // 如果是字符串，尝试解析
				    if (typeof userInfoStr === 'string') {
				      const parsed = JSON.parse(userInfoStr)
				      // 检查是否是登录响应格式
				      if (parsed.code === 200 && parsed.data) {
				        userInfo = parsed.data
				      } else {
				        userInfo = parsed
				      }
				    } else {
				      // 如果不是字符串，直接使用
				      userInfo = userInfoStr
				    }
				  } catch (e) {
				    console.error('解析用户信息失败', e)
				    // 解析失败时，尝试直接使用
				    userInfo = userInfoStr
				  }
				}
				const params = { status: this.currentStatus };
				if (userInfo && userInfo.techId) {
					params.technicianId = userInfo.techId;
				} else if (userInfo && userInfo.memberId) {
					params.userId = userInfo.memberId;
				}
				const res = await uni.request({
					url: `${uni.$config.baseUrl}/aftersales/aftersales/listAll`,
					method: 'GET',
					data: params
				})
				console.log(res)
				if (res.data.code === 200) {
					// 添加数据验证，确保每个项目都有必要的字段
					this.reportList = (res.data.rows || []).map(item => {
						// 确保各对象存在
						if (!item.project) item.project = {};
						if (!item.store) item.store = {};
						if (!item.technician) item.technician = {};
						
						// 确保其他必要字段有默认值
						if (!item.feedbackTypes) item.feedbackTypes = '';
						if (!item.feedbackContent) item.feedbackContent = '';
						// 去除反馈内容中的 HTML 标签（如 <p></p>）
						item.feedbackContent = item.feedbackContent.replace(/<[^>]+>/g, '')
						
						return item;
					});
					
					if(tag==1){
						this.loadStatusCount() // 在获取列表后更新状态数量
					}
					
				} else {
					uni.showToast({
						title: res.data.msg || '获取列表失败',
						icon: 'none'
					})
				}
			} catch (error) {
				uni.showToast({
					title: '网络请求失败',
					icon: 'none'
				})
			}
		},

		// 加载状态数量
		loadStatusCount() {
			// 计算每个状态的数量
			const counts = {
				'-1': this.reportList.length, // 全部数量
				'0': 0,  // 待处理
				'1': 0,  // 处理中
				'2': 0,  // 已完成
				'3': 0   // 已驳回
			}
			
			// 统计各状态数量
			this.reportList.forEach(item => {
				if (counts.hasOwnProperty(item.status)) {
					counts[item.status]++
				}
			})
			
			// 更新状态标签的数量
			this.statusTabs = this.statusTabs.map(tab => ({
				...tab,
				count: counts[tab.value]
			}))
		},

		// 获取状态文本
		getStatusText(status) {
			const statusMap = {
				0: '待处理',
				1: '处理中',
				2: '已完成',
				3: '已驳回'
			}
			return statusMap[status] || '未知状态'
		},

		// 预览图片
		previewImage(urls, current) {
			if (!urls || !urls.length) return;
			
			uni.previewImage({
				urls: urls,
				current: urls[current] || urls[0]
			})
		},

		// 判断是否为图片URL
		isImageUrl(url) {
			if (!url) return false;
			
			const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif'];
			const extension = url.substring(url.lastIndexOf('.')).toLowerCase();
			return imageExtensions.includes(extension);
		}
	}
}
</script>

<style lang="scss">
.report-list {
	min-height: 100vh;
	background: #F8F8F8;
	padding-bottom: 20rpx;

	.status-tabs {
		display: flex;
		background: #FFFFFF;
		padding: 20rpx 0;
		position: sticky;
		top: 0;
		z-index: 100;

		.tab-item {
			flex: 1;
			display: flex;
			justify-content: center;
			font-size: 28rpx;
			color: #666;
			position: relative;

			.tab-content {
				display: flex;
				align-items: center;
			}

			&.active {
				color: #2B87FF;
				font-weight: 500;

				&::after {
					content: '';
					position: absolute;
					bottom: -10rpx;
					left: 50%;
					transform: translateX(-50%);
					width: 40rpx;
					height: 4rpx;
					background: #2B87FF;
					border-radius: 2rpx;
				}
			}

			.count {
				font-size: 24rpx;
				margin-left: 4rpx;
			}
		}
	}

	.report-items {
		padding: 20rpx;

		.report-item {
			background: #FFFFFF;
			border-radius: 12rpx;
			padding: 30rpx;
			margin-bottom: 20rpx;

			.service-info {
				display: flex;
				margin-bottom: 20rpx;
				position: relative;

				.service-image {
					width: 160rpx;
					height: 160rpx;
					border-radius: 8rpx;
					margin-right: 20rpx;
				}

				.service-content {
					flex: 1;

					.service-title {
						font-size: 32rpx;
						color: #333;
						font-weight: 500;
						margin-bottom: 12rpx;
					}

					.service-meta {
						font-size: 26rpx;
						color: #666;
						margin-bottom: 8rpx;

						.technician {
							margin-left: 20rpx;
						}
					}

					.service-time {
						font-size: 24rpx;
						color: #999;
					}
				}

				.status-tag {
					position: absolute;
					right: 0;
					top: 0;
					padding: 4rpx 16rpx;
					border-radius: 24rpx;
					font-size: 24rpx;

					&.pending {
						background: #FFF7E6;
						color: #FA8C16;
					}

					&.processing {
						background: #E6F7FF;
						color: #1890FF;
					}

					&.completed {
						background: #F6FFED;
						color: #52C41A;
					}

					&.rejected {
						background: #FFF1F0;
						color: #F5222D;
					}
				}
			}

			.feedback-info {
				border-top: 2rpx solid #F5F5F5;
				padding-top: 20rpx;

				.feedback-types {
					display: flex;
					flex-wrap: wrap;
					margin-bottom: 16rpx;

					.type-tag {
						background: #F5F5F5;
						color: #666;
						font-size: 24rpx;
						padding: 4rpx 16rpx;
						border-radius: 24rpx;
						margin-right: 12rpx;
						margin-bottom: 12rpx;
					}
				}

				.feedback-content {
					font-size: 28rpx;
					color: #333;
					line-height: 1.6;
					margin-bottom: 16rpx;
				}

				.media-list {
					display: flex;
					flex-wrap: wrap;
					margin: 12rpx 0;

					.media-item {
						width: 160rpx;
						height: 160rpx;
						margin-right: 12rpx;
						margin-bottom: 12rpx;
						position: relative;
						overflow: hidden;

						.feedback-image,
						.feedback-video {
							width: 100%;
							height: 100%;
							border-radius: 8rpx;
							object-fit: cover;
						}

						&:last-child {
							margin-right: 0;
						}
					}
				}
			}

			.handle-result {
				margin-top: 20rpx;
				padding-top: 20rpx;
				border-top: 2rpx solid #F5F5F5;

				.result-title {
					font-size: 28rpx;
					color: #333;
					font-weight: 500;
					margin-bottom: 12rpx;
				}

				.result-content {
					font-size: 28rpx;
					color: #666;
					line-height: 1.6;
					margin-bottom: 12rpx;
				}

				.handle-time {
					font-size: 24rpx;
					color: #999;
				}
			}
		}
	}

	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding-top: 200rpx;

		image {
			width: 200rpx;
			height: 200rpx;
			margin-bottom: 20rpx;
		}

		text {
			font-size: 28rpx;
			color: #999;
		}
	}
}
</style> 